package top.kikt.book.core.template

import top.kikt.book.core.base.BookChapterHandler
import top.kikt.book.core.base.IBookHandler
import top.kikt.book.core.entity.BookEntity
import java.io.File
import java.nio.charset.StandardCharsets

class TextTemplate(private val bookChapterHandler: BookChapterHandler) : OutputTemplate {

    override fun fileExt(): String = "txt"

    override fun write(bookHandler: IBookHandler, entity: BookEntity, outputPath: String): File {
        val outputFile = File(getOutputFilePath(bookHandler, entity, outputPath))

        if (outputFile.exists()) {
            outputFile.delete()
        }

        if (outputFile.parentFile?.exists() == false) {
            outputFile.parentFile?.mkdirs()
        }

        outputFile.createNewFile()
        val writer = outputFile.writer()

        for (chapterMeta in entity.chapterMetaEntityList) {
            val file = entity.getFile(chapterMeta) ?: continue

            if (bookHandler.outputChapterTitle()) {
                val titleName = bookChapterHandler.getOutputChapterTitle(chapterMeta)
                writer.append(titleName)
                writer.append("\n\n")
            }

            val text = bookHandler.replaceWatermark(file.readText().handleText())
                .removeEmptyLines()

            writer.append(text)
            writer.append("\n\n")
        }

        logger.info("${outputFile.absolutePath} 写入完成")

        writer.close()
        return outputFile
    }

    private fun String.handleText(): String {
        val bytes2 = byteArrayOf(0xC2.toByte(), 0xA0.toByte())
        val space = String(bytes2, StandardCharsets.UTF_8)
        return replace(space, "")
    }
}

private fun String.removeEmptyLines(): String {
    return this.split("\n")
        .filter { it.trim().isNotEmpty() }
        .joinToString("\n")
}
